package com.rlz.base.util.download.db;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.rlz.base.util.download.config.InnerConstant;
import com.rlz.libs.log.P;

/**
 * Created by RLZ
 * on 2021/4/22
 */
public class DbOpenHelper extends SQLiteOpenHelper {
    public static final String TAG = "DbOpenHelper";

    public DbOpenHelper(Context context) {
        super(context, InnerConstant.Db.NAME_DB, null, getVersionCode(context));
    }

    private static int getVersionCode(Context context){
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionCode;
        }catch (Exception e){
            P.e(TAG, "创建数据库失败 ");
            e.printStackTrace();
        }
        return 0;
    }


    @Override
    public void onCreate(SQLiteDatabase db) {
        String info = "create table if not exists " + InnerConstant.Db.NAME_TABLE
                + "(" +
                InnerConstant.Db.ID + " varchar(500)," +
                InnerConstant.Db.DOWNLOAD_URL + " varchar(100)," +
                InnerConstant.Db.FILE_PATH + " varchar(100)," +
                InnerConstant.Db.SIZE + " integer," +
                InnerConstant.Db.DOWNLOAD_LOCATION + " integer," +
                InnerConstant.Db.DOWNLOAD_STATUS + " integer)";

        P.i(TAG, "onCreate() -> info=" + info);
        db.execSQL(info);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        //直接删除重新建表
        db.execSQL("drop table if exists " + InnerConstant.Db.NAME_TABLE);
        onCreate(db);
    }
}
